package i18n

import (
	"strings"

	"gitee.com/sansaniot/ssiot-core/config"
	"gitee.com/sansaniot/ssiot-core/logger"
	"gitee.com/sansaniot/ssiot-core/utils"
	"github.com/gogf/gf/v2/i18n/gi18n"
	"github.com/gogf/gf/v2/os/gctx"
)

var (
	ctx     = gctx.New()
	i18nMng = gi18n.New()

	// 默认与settings.yml一个路径
	defaultPath = ""
)

func SetupI18n(configFilePath string) {
	// 默认中文
	defaultLang := utils.If(len(config.I18nConfig.DefaultLocale) == 0, "zh-CN", config.I18nConfig.DefaultLocale).(string)
	i18nMng.SetLanguage(defaultLang)
	logger.Infof("system default locale:  %s", utils.Green(defaultLang))

	if len(config.I18nConfig.Path) == 0 {
		// 不指定路径，默认与settings.yml一个路径
		config.I18nConfig.Path = configFilePath[:strings.LastIndex(configFilePath, "/")]
	}
	// 可自定义路径
	if err := i18nMng.SetPath(config.I18nConfig.Path); err != nil {
		logger.Errorf("i18n file path err: %v", err.Error())
	} else {
		logger.Infof("i18n file path:  %s", utils.Green(config.I18nConfig.Path))
	}
	i18nMng.SetDelimiters("{$", "}")
}

func T(lang, key string) string {
	return i18nMng.Translate(gi18n.WithLanguage(ctx, lang), key)
}

func Tf(lang string, key string, values ...interface{}) string {
	rs := i18nMng.TranslateFormat(gi18n.WithLanguage(ctx, lang), key, values...)
	if strings.Contains(rs, "%!") {
		rs = strings.Split(rs, "%!")[0]
	}
	return rs
}
